<?php
namespace yimishiji\YSCApi\components;

use Composer\Script\Event;

/**
 * Site controller
 */
class ComposerEvent
{
    public static function postCreateProject(Event $event)
    {
        $namespace =  $event->getIO()->ask('plase input your\'s project namespace?', "newproject");
        $basePath = dirname($event->getComposer()->getConfig()->get('vendor-dir'));

        self::replaseNameSpace($basePath, $namespace);
        exit;
        // do stuff
    }

    public static function replaseNameSpace($path, $namespace)
    {
        if(!is_dir($path))
            return false;

        $files = scandir($path);

        foreach ($files as $file)
        {
            if(in_array($file, ['vendor', '.git', '.', '..'])){
                continue;
            }

            $fileName =  "{$path}/$file";

            if(is_dir($fileName)) {
                self::replaseNameSpace($fileName, $namespace);
                continue;
            }

            $ext = pathinfo($fileName,PATHINFO_EXTENSION);
            if(in_array($ext, ['ico', 'jpg'])){
                continue;
            }

            $fileContent = file_get_contents($fileName);
            if(strpos($fileContent, '{varappmoudle}')===false){
                continue;
            }


            $content = str_replace('{varappmoudle}', $namespace, $fileContent);
            file_put_contents($fileName, $content);

            echo "replase file:  $fileName \n";
        }
    }


}